package edu.bu.manateem.msg.analysis.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import edu.bu.manateem.msg.MSGConstants;
import edu.bu.manateem.msg.model.Compound;
import edu.bu.manateem.msg.model.CompoundParent;
import edu.bu.manateem.msg.util.ChemicalFormulaUtils;

import org.apache.commons.lang.StringUtils;

/**
 * 
 * @author gindiny
 *
 */
public class ReadTargets
{
	final static int NAME_COLUMN = 0;
	final static int FORMULA_COLUMN = 1;
	final static int CHARGE_COLUMN = 2;
	final static int RETENTION_TIME_COLUMN = 3;
	final static int NUMBER_OF_COLUMNS = 4;
	
	/**
	 * Parses the input and returns the a <code>List</code>
	 * populated with <code>Molecule</code> <code>Object</code>s
	 * @param fileName
	 * @return
	 */
	public static List<CompoundParent> getMoleculeSpeciesData(String fileName)
	{
		List<CompoundParent> compoundParents = new ArrayList<CompoundParent>();
		BufferedReader in;
		try
		{
			in = new BufferedReader(new FileReader(fileName));
			String line;
			while ((line = in.readLine()) != null)
			{
				final String[] columns =
					StringUtils.split(line,MSGConstants.TAB);
				if (columns.length != ReadTargets.NUMBER_OF_COLUMNS)
				{
					continue;
				}
				
				String name = columns[ReadTargets.NAME_COLUMN];
				Map<String,Integer> formula =
					ChemicalFormulaUtils.parseChemFormula(columns[ReadTargets.FORMULA_COLUMN]);
				int charge =
					Integer.parseInt(columns[ReadTargets.CHARGE_COLUMN]);
				double retentionTime =
					Double.parseDouble(columns[ReadTargets.RETENTION_TIME_COLUMN]);
				Compound compound =
					new Compound(formula,charge,retentionTime,name);
				
				// is this a new group (parent)?
				CompoundParent molecule =
					new CompoundParent(columns[ReadTargets.NAME_COLUMN]);
				if (!compoundParents.contains(molecule))
				{
					compoundParents.add(molecule);
				}
				
				compoundParents.get(compoundParents.indexOf(molecule)).addCompound(
					compound);
				
			}
			return compoundParents;
			
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return compoundParents;
	}
}
